package dungnt.vpoint.mathtest;

import java.text.SimpleDateFormat;


import dungnt.vpoint.mathtest.db.ScoreDatabase;
import dungnt.vpoint.mathtest.dialog.Top50Dialog;

import dungnt.vpoint.mathtest.util.Operate;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class GameMode extends Activity implements OnClickListener {

	Operate expression;
	Typeface tp;
	ImageView imgOperatorTitle;
	ImageView imgOperator;
	ImageView imgSecondHand;
	EditText txtYourName;
	Button btnNum0, btnNum1, btnNum2, btnNum3, btnNum4, btnNum5, btnNum6, btnNum7, btnNum8, btnNum9, btnDel, btnEnter, btnNegative, btnHome;
	TextView lblResult, lblFirstOperand, lblSecondOperand, lblScore;
	Dialog leaderboard_dialog;
	Button btnNoThanks, btnSubmitScore;
	int score = 0;
	int op;
	boolean negative = false;
	private final int timeDuration = 20000;
	private MyTimer myTimer;
	Intent i_play;
	public static int topScore;
	String userName = null;
	String time = null;
	private ScoreDatabase scoreData;
	String temp1;

	// Array of operators

	int[] arr_operators = new int[] { R.drawable.add_operator, // "+"
			R.drawable.sub_operator, // "-"
			R.drawable.multi_operator, // "*"
			R.drawable.div_operator // "/"
	};

	// Array of operator titles

	int[] arr_operator_titles = new int[] { R.drawable.add_title, // "add"
			R.drawable.subtract_title, // "subtract"
			R.drawable.multiply_title, // "multiply"
			R.drawable.divide_title, // "divide"
			R.drawable.final_test_title // "final test"
	};

	// Array of name test
	String[] arr_name_tests = new String[] { "Add", "Subtract", "Multiply",
			"Divide", "Final" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.game_mode);

		expression = new Operate();
		//initialize database
		scoreData = new ScoreDatabase(this);
		// get View from layout
		lblResult = (TextView) findViewById(R.id.lblResult);
		lblScore = (TextView) findViewById(R.id.lblScore);
		lblFirstOperand = (TextView) findViewById(R.id.lblFirstOperand);
		lblSecondOperand = (TextView) findViewById(R.id.lblSecondOperand);
		imgSecondHand = (ImageView) findViewById(R.id.imgSecondHand);

		// "keyboard"
		btnNum0 = (Button) findViewById(R.id.btnNum0);
		btnNum1 = (Button) findViewById(R.id.btnNum1);
		btnNum2 = (Button) findViewById(R.id.btnNum2);
		btnNum3 = (Button) findViewById(R.id.btnNum3);
		btnNum4 = (Button) findViewById(R.id.btnNum4);
		btnNum5 = (Button) findViewById(R.id.btnNum5);
		btnNum6 = (Button) findViewById(R.id.btnNum6);
		btnNum7 = (Button) findViewById(R.id.btnNum7);
		btnNum8 = (Button) findViewById(R.id.btnNum8);
		btnNum9 = (Button) findViewById(R.id.btnNum9);
		btnDel = (Button) findViewById(R.id.btnDel);
		btnNegative = (Button) findViewById(R.id.btnNegative);
		btnEnter = (Button) findViewById(R.id.btnEnter);
		btnHome = (Button) findViewById(R.id.btnHome);

		// event handler
		btnNum0.setOnClickListener(this);
		btnNum1.setOnClickListener(this);
		btnNum2.setOnClickListener(this);
		btnNum3.setOnClickListener(this);
		btnNum4.setOnClickListener(this);
		btnNum5.setOnClickListener(this);
		btnNum6.setOnClickListener(this);
		btnNum7.setOnClickListener(this);
		btnNum8.setOnClickListener(this);
		btnNum9.setOnClickListener(this);
		btnDel.setOnClickListener(this);
		btnNegative.setOnClickListener(this);
		btnEnter.setOnClickListener(this);
		btnHome.setOnClickListener(this);
		
		leaderboard_dialog = new Dialog(this);
		leaderboard_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		leaderboard_dialog.setContentView(R.layout.leaderboard_dialog);
		leaderboard_dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
		btnNoThanks = (Button)leaderboard_dialog.findViewById(R.id.btnNo_Thanks);
		btnSubmitScore = (Button)leaderboard_dialog.findViewById(R.id.btnSubmitScore);
		
		btnNoThanks.setOnClickListener(this);
		btnSubmitScore.setOnClickListener(this);

		// get operator from PlayActivity
		Intent i = getIntent();
		op = Integer.valueOf(i.getStringExtra("operator"));
		expression.setOperator(op);

		// set name and operator for test
		imgOperatorTitle = (ImageView) findViewById(R.id.imgOperatorTitle);
		imgOperator = (ImageView) findViewById(R.id.imgOperator);
		setTestName(op);

		// set font to textview
		setFont();

		showClock();
	}

	private void showClock() {
		myTimer = new MyTimer(timeDuration, 1000);
		timer();
		myTimer.start();
	}

	private void setTestName(int op) {
		switch (op) {
		case 0:
			imgOperatorTitle.setImageResource(arr_operator_titles[op]);
			imgOperator.setImageResource(arr_operators[op]);
			btnNegative.setVisibility(View.GONE);
			// generate random operand
			genExpression();
			break;
		case 1:
			imgOperatorTitle.setImageResource(arr_operator_titles[op]);
			imgOperator.setImageResource(arr_operators[op]);
			// generate random operand
			genExpression();
			break;
		case 2:
			imgOperatorTitle.setImageResource(arr_operator_titles[op]);
			imgOperator.setImageResource(arr_operators[op]);
			btnNegative.setVisibility(View.GONE);
			// generate random operand
			genExpression();
			break;
		case 3:
			imgOperatorTitle.setImageResource(arr_operator_titles[op]);
			imgOperator.setImageResource(arr_operators[op]);
			btnNegative.setVisibility(View.GONE);
			// generate random operand
			genExpression();
			break;
		case 4:
			imgOperatorTitle.setImageResource(arr_operator_titles[op]);
			// display negative button if operator is subtract
			expression.generateOperator();
			imgOperator.setImageResource(arr_operators[expression.getOperator()]);
			if (expression.getOperator() != 1) {
				btnNegative.setVisibility(View.GONE);
			} else {
				btnNegative.setVisibility(View.VISIBLE);
			}
			// generate random operand
			genExpression();
			break;
		}
	}

	
	private void genExpression() {
		// generate two operand
		do {
			expression.generateOperand();
		} while (expression.checkDuplicate(expression.getFirstNumber(), expression.getSecondNumber()));
		
		lblFirstOperand.setText(String.valueOf(expression.getFirstNumber()));
		lblSecondOperand.setText(String.valueOf(expression.getSecondNumber()));
	}

	private void timer() {
		imgSecondHand = (ImageView) findViewById(R.id.imgSecondHand);
		Animation clock = new RotateAnimation(0f, 360f,Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);
		clock.setDuration(timeDuration);
		imgSecondHand.startAnimation(clock);
	}

	@Override
	public void onClick(View v) {
		String temp="";
		switch (v.getId()) {
		case R.id.btnNum0:
			temp = lblResult.getText().toString();
			lblResult.setText(temp + "0");
			temp1 = lblResult.getText().toString();
			break;
		case R.id.btnNum1:
			temp = lblResult.getText().toString();
			lblResult.setText(temp + "1");
			temp1 = lblResult.getText().toString();
			break;
		case R.id.btnNum2:
			temp = lblResult.getText().toString();
			lblResult.setText(temp + "2");
			temp1 = lblResult.getText().toString();
			break;
		case R.id.btnNum3:
			temp = lblResult.getText().toString();
			lblResult.setText(temp + "3");
			temp1 = lblResult.getText().toString();
			break;
		case R.id.btnNum4:
			temp = lblResult.getText().toString();
			lblResult.setText(temp + "4");
			temp1 = lblResult.getText().toString();
			break;
		case R.id.btnNum5:
			temp = lblResult.getText().toString();
			lblResult.setText(temp + "5");
			temp1 = lblResult.getText().toString();
			break;
		case R.id.btnNum6:
			temp = lblResult.getText().toString();
			lblResult.setText(temp + "6");
			temp1 = lblResult.getText().toString();
			break;
		case R.id.btnNum7:
			temp = lblResult.getText().toString();
			lblResult.setText(temp + "7");
			temp1 = lblResult.getText().toString();
			break;
		case R.id.btnNum8:
			temp = lblResult.getText().toString();
			lblResult.setText(temp + "8");
			temp1 = lblResult.getText().toString();
			break;
		case R.id.btnNum9:
			temp = lblResult.getText().toString();
			lblResult.setText(temp + "9");
			temp1 = lblResult.getText().toString();
			break;
		case R.id.btnDel:
			temp = "";
			lblResult.setText(temp);
			break;
		case R.id.btnNegative:
			if (lblResult.getText().toString().equals("")) {
				temp = "";
				lblResult.setText(temp);
				break;
			}
			
			if (lblResult.getText().toString().equals("0")) {
				temp = "0";
				lblResult.setText(temp);
				break;
			}
			
			if (!lblResult.getText().toString().contains("-")) {
				temp = "-" + temp1;
				lblResult.setText(temp);
				break;
			}
			
			if (!lblResult.getText().toString().equals("") && lblResult.getText().toString().contains("-")){
				lblResult.setText(temp1);
				break;
			}
		case R.id.btnEnter:
			int kq;
			if (lblResult.getText().toString().equals(""))
				kq = 0;
			else
				kq = Integer.valueOf(lblResult.getText().toString());

			if (expression.checkAnswer(kq)) {
				score++;
				lblScore.setText(String.valueOf(score));
			}
			// generate random operator if test is final test
			if (op == 4) {
				// display negative button if operator is subtract
				expression.generateOperator();
				imgOperator.setImageResource(arr_operators[expression.getOperator()]);
				if (expression.getOperator() != 1) {
					btnNegative.setVisibility(View.GONE);
				} else {
					btnNegative.setVisibility(View.VISIBLE);
				}
			}
			// generate next expression
			genExpression();
			// reset result
			lblResult.setText("");
			break;
		case R.id.btnHome:
			myTimer.cancel();
			i_play = new Intent(this, PlayActivity.class);
			startActivity(i_play);
			finish();
			break;
		case R.id.btnNo_Thanks:
			leaderboard_dialog.dismiss();
			i_play = new Intent(this, PlayActivity.class);
			startActivity(i_play);
			finish();
			break;
		case R.id.btnSubmitScore:
			//Save score to database
			SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
			java.util.Date date = new java.util.Date();
			time = "" + dateFormat.format(date);
			userName = txtYourName.getText().toString().trim();
			// saveData;
			scoreData.openDB();
			scoreData.insert(op, userName, score, time);
			scoreData.closeDB();
			topScore = score;
			leaderboard_dialog.dismiss();
			Intent i = new Intent(this, Top50Dialog.class);
			startActivity(i);
			finish();
			//score=0;
			break;
		}
	}

	private void setFont() {
		tp = Typeface.createFromAsset(getAssets(), "chalkdust.ttf");

		lblFirstOperand.setTypeface(tp);
		lblSecondOperand.setTypeface(tp);
		lblResult.setTypeface(tp);
		lblScore.setTypeface(tp);
	}

	private void showLeaderBoard() {
		TextView lblTitle, lblNameTest, lblYourScore, lblScore, lblSave, lblLevel, lblDescription, lblCurrentLevel;
		final int ptUnit = TypedValue.COMPLEX_UNIT_PT;

		// set title
		lblTitle = (TextView) leaderboard_dialog.findViewById(R.id.lblLeaderBoardTitle);
		tp = Typeface.createFromAsset(getAssets(), "MYRIADPRO-REGULAR.OTF");
		lblTitle.setTypeface(tp);
		lblTitle.setText("Leaderboard");
		// lblTitle.setTextSize(ptUnit,8.78f);
		// name test
		lblNameTest = (TextView) leaderboard_dialog.findViewById(R.id.lblNameTest);
		tp = Typeface.createFromAsset(getAssets(), "arial_regular.ttf");
		lblNameTest.setTypeface(tp);
		lblNameTest.setText("Math Test: " + arr_name_tests[op] + " Test Score");
		// lblNameTest.setTextSize(ptUnit, 7.5f);
		// you scored
		lblYourScore = (TextView) leaderboard_dialog.findViewById(R.id.lblYourScore);
		tp = Typeface.createFromAsset(getAssets(), "MYRIADPRO-REGULAR.OTF");
		lblYourScore.setTypeface(tp);
		lblYourScore.setText("You Scored:");
		// lblYourScore.setTextSize(ptUnit, 5.78f);
		// Score
		lblScore = (TextView) leaderboard_dialog.findViewById(R.id.lblScore);
		tp = Typeface.createFromAsset(getAssets(), "arial_rounded_mt_bold.ttf");
		lblScore.setTypeface(tp);
		lblScore.setText(String.valueOf(score));
		// lblScore.setTextSize(ptUnit, 19.5f);
		// Save
		lblSave = (TextView) leaderboard_dialog.findViewById(R.id.lblSave);
		tp = Typeface.createFromAsset(getAssets(), "arial_regular.ttf");
		lblSave.setTypeface(tp);
		lblSave.setText("Save score as guests");
		// lblSave.setTextSize(ptUnit, 6.83f);
		// Level
		lblLevel = (TextView) leaderboard_dialog.findViewById(R.id.lblLevel);
		tp = Typeface.createFromAsset(getAssets(), "arial_regular.ttf");
		lblLevel.setTypeface(tp);
		lblLevel.setText("Level:");
		// lblLevel.setTextSize(ptUnit, 6.83f);
		// Current level
		lblCurrentLevel = (TextView) leaderboard_dialog.findViewById(R.id.lblCurrentLevel);
		tp = Typeface.createFromAsset(getAssets(), "arial_regular.ttf");
		lblCurrentLevel.setTypeface(tp);
		lblCurrentLevel.setText(String.valueOf(expression.getLevel()));
		// lblCurrentLevel.setTextSize(ptUnit, 10f);
		// Save description
		lblDescription = (TextView) leaderboard_dialog.findViewById(R.id.lblDescription);
		tp = Typeface.createFromAsset(getAssets(), "arial_regular.ttf");
		lblDescription.setTypeface(tp);
		lblDescription.setText("Save score to your gamer profile");
		// lblDescription.setTextSize(ptUnit, 6.83f);
		// enter name
		txtYourName = (EditText) leaderboard_dialog.findViewById(R.id.txtYourName);
		txtYourName.setTextSize(ptUnit, 6.83f);

		leaderboard_dialog.show();
		
	}

	private class MyTimer extends CountDownTimer {

		public MyTimer(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onFinish() {

			showLeaderBoard();
			myTimer.cancel();

		}

		@Override
		public void onTick(long arg0) {
			// TODO Auto-generated method stub

		}

	}

	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent i = new Intent(this, PlayActivity.class);
            startActivity(i);
            finish();
        }
        
        return super.onKeyDown(keyCode, event);
    }
}
